package cn.yudao.basic.interceptor;

import cn.yudao.basic.annotation.PreAuthorize;
import cn.yudao.basic.jwt.JwtUtils;
import cn.yudao.basic.jwt.Payload;
import cn.yudao.basic.jwt.RsaUtils;
import cn.yudao.basic.jwt.UserInfo;
import cn.yudao.system.mapper.PermissionMapper;
import cn.yudao.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String pubKey;

    /**
     * @Title: preHandle
     * @Description: token无状态拦截器
     * @Author: Mr.Jia
     * @Version: 1.0
     * @Date: 2022/7/14 18:34
     * @Parameters:
     * @Return
     */
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        // 设置字符集
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json;charset=UTF-8");
//        // 从请求头获取token
//        String token = request.getHeader("token");
//        // 判断token是否存在
//        if (token !=null){
//            // 冲redis中获取值
//            Object logininfo = redisTemplate.opsForValue().get(token);
//
//            // 判断；logininfo是否有值
//            if (logininfo != null){
//                Logininfo logininfo1 = new Logininfo();
//                BeanUtils.copyProperties(logininfo,logininfo1);
//                if (logininfo1.getType() == 0){
//                    // 判断用户是否具有权限
//                    HandlerMethod methodHandle = (HandlerMethod) handler;
//                    // 获得接口
//                    PreAuthorize methodAnnotation = methodHandle.getMethodAnnotation(PreAuthorize.class);
//                    if (methodAnnotation != null){
//                        // 获取的权限的sn
//                        String sn = methodAnnotation.sn();
//                        // 根据logininfoid获得对应角色的权限sn集合
//                        List<String> sns =  permissionMapper.loadPermissionBylogininfoId(logininfo1.getId());
//                        // 判断接口的sn在不在sns中以次确定用户是否有权限
//                        if (!sns.contains(sn)){
//                            //获取到打印流,并设置响应数据
//                            PrintWriter writer = response.getWriter();
//                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
//                            //刷新、关流
//                            writer.flush();
//                            writer.close();
//                            return false;
//                        }
//                    }
//                }
//                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//                return true;
//            }
//        }
//
//        //获取到打印流,并设置响应数据
//        PrintWriter writer = response.getWriter();
//        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
//        //刷新、关流
//        writer.flush();
//        writer.close();
//        return false;
//    }


    /**
     * @Title: preHandle
     * @Description: Jwt登录拦截器
     * @Author: Mr.Jia
     * @Version: 1.0
     * @Date: 2022/7/14 18:35
     * @Parameters:
     * @Return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置字符集
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        // 从请求头获取token
        String token = request.getHeader("token");
        // 判断token是否存在
        if (token != null) {
            // 先获取etPrivateKey(JwtUtils.class.getClassLoader().getResource(BaseConstants.JwtConstant.JWT_AUTH_PRIKEY).getFile());
            // 获取logininfo从jwt字符串中
            // 2 解析token里面内容
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(pubKey).getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            Logininfo logininfo = payload.getUserInfo().getLogininfo();
            // 判断；logininfo是否有值
            // 判断登录用户类型是员工还是用户
            if (logininfo.getType() == 0) { //==0是表示是员工
                // 判断用户是否具有权限
                HandlerMethod methodHandle = (HandlerMethod) handler;
                // 获得接口
                PreAuthorize methodAnnotation = methodHandle.getMethodAnnotation(PreAuthorize.class);
                if (methodAnnotation != null) {
                    // 获取的权限的sn
                    String sn = methodAnnotation.sn();
                    // 获取token中加密的permissionsns
                    List<String> permissions = payload.getUserInfo().getPermissions();
                    // 判断接口的sn在不在sns中以次确定用户是否有权限
                    if (!permissions.contains(sn)) {
                        //获取到打印流,并设置响应数据
                        PrintWriter writer = response.getWriter();
                        writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                        //刷新、关流
                        writer.flush();
                        writer.close();
                        return false;
                    }
                }
            }
            // 重写设置jwt更新时间
            return true;

        }

        //获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        //刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}
